import './index.less';
import React, { useState, useEffect } from 'react';
import ZhCN from 'antd/lib/locale/zh_CN';
import {
  Table,
  Input,
  Button,
  message,
  Modal,
  Divider,
  Card,
  Form,
  Col,
  Row,
  Select,
  Tabs,
  Space,
  Switch,
  Pagination,
  ConfigProvider,
} from 'antd';
import columnsData from './data';
import Flow from '../Flow/index.js';
import {
  OrchestrationAdd,
  OrchestrationDelete,
  OrchestrationEdit,
  OrchestrationList,
  OrchestrationView,
} from '../api/Orchestration';
import {
  editChoreographyJSON,
  choreographyAdd,
} from '../api/ChoreographyMachine';

const index = () => {
  // 根据条件查询的列表数据
  const [datas, setDatas] = useState([]);
  // 删除提示框显示状态
  const [isModalVisible, setIsModalVisible] = useState(false);
  // 删除列表项ID
  const [deleteid, setDeleteid] = useState();
  // 查询条件应用ID
  const [appId, setAppId] = useState('');
  // 查询条件服务名
  const [choreographyServiceName, setChoreographyServiceName] = useState('');
  // 查询条件方法名
  const [choreographyMethodName, setChoreographyMethodName] = useState('');
  // 查询条件当前页
  const [currentPageNo, setCurrentPageNo] = useState(1);
  // 查询条件页大小
  const [pageSize, setPageSize] = useState(10);
  // 列表总条数
  const [listTotal, setListTotal] = useState(1);
  // 用户添加模态框显示状态
  const [addModal, setAddModal] = useState(false);
  // 用户编辑模态框显示状态
  const [editModal, setEditModal] = useState(false);
  // 添加用户数据表单验证
  const addFormRef: any = React.createRef();
  // 用户数据修改表单交互
  const [editForm] = Form.useForm();
  // 添加确认后的模态框显示状态
  const [isModalServer, setIsModalServer] = useState(false);
  // 添加确认后返回的用于添加服务编排的id
  const [addAfterId, setAddAfterId] = useState('');
  // 修改编排模态框显示状态
  const [choreographyEdit, setChoreographyEdit] = useState(false);
  // 修改编排模态框id
  const [editChoreographyDataId, setEditChoreographyDataId] = useState(false);
  // 查看模态框是否显示
  const [ViewModal, setViewModal] = useState(false);
  const [showFlow, setShowFlow] = useState(false);

  // 用户查看列表项交互
  const [viewForm] = Form.useForm();
  // 服务编排传来的编排好的参数
  const [childDatas, setChildDatas] = useState({});
  // 修改编排的初始数据
  const [serverData, setServerData] = useState({});
  // 刷新子组件计数器
  const [refreshNum, setRefreshNum] = useState(0);

  // 导出组件方法
  const { Column, ColumnGroup } = Table;
  const { TabPane } = Tabs;
  const { Option } = Select;

  /**
   *  @description 表格组装
   */

  // table表格组合操作
  const columns = columnsData;
  // 定义操作行
  const columnsActionRender: any = {
    action: (text: any, record: any, index: number) => (
      <div>
        <a onClick={() => viewUser(record.id)}>查看</a>
        <Divider type="vertical" />
        <a onClick={() => editUser(record)}>修改</a>
        <Divider type="vertical" />
        <a onClick={() => handleRemove(record.id)}>删除</a>
        <Divider type="vertical" />
        <a onClick={() => editChoreography(record.id)}>编排设计</a>
      </div>
    ),
  };
  // 表格头部数据
  columns.forEach((item: any) => {
    if (item.dataIndex === 'action')
      item.render = columnsActionRender[item.dataIndex];
  });

  /**
   *  @description API请求函数
   */

  // 列表请求函数
  const getDatas = (valOne: any, valTwo: any) => {
    try {
      OrchestrationList(valOne, valTwo).then((val) => {
        // console.log(val);
        setDatas(val.data);
        setListTotal(val.pagination.totalSize);
      });
    } catch (error) {}
  };

  // 添加编排服务函数
  const addDatas = (val: any) => {
    try {
      OrchestrationAdd(val).then((val) => {
        console.log(val.data);
        setAddAfterId(val.data.id);
        // console.log(addAfterId);
        refreshList();
        setAddModal(false);
        setIsModalServer(true);
      });
    } catch (error) {}
  };

  // 删除编排服务函数
  const deleteDatas = (val: any) => {
    try {
      OrchestrationDelete(val).then((val) => {
        setIsModalVisible(false);
        refreshList();
      });
    } catch (error) {}
  };

  // 修改编排服务函数
  const editDatas = (val: any) => {
    try {
      OrchestrationEdit(val).then((res) => {
        refreshList();
      });
    } catch (error) {}
  };

  // 查看编排服务函数
  const viewDatas = (val: any) => {
    try {
      OrchestrationView(val).then((res) => {
        viewForm.setFieldsValue(val.data);
      });
    } catch (error) {}
  };

  // 设置编排机JSON
  const setChoreographyApi = (val: any) => {
    try {
      choreographyAdd(val).then((res) => {
        setIsModalServer(false);
        message.success('添加成功');
        setServerData({});
      });
    } catch (error) {}
  };

  // 回显编排机
  const viewOrchestrationDatas = (val: any) => {
    try {
      OrchestrationView(val).then((res) => {
        const parmJSON = JSON.parse(res.data.stateMachineJson);
        console.log(parmJSON);
        setServerData(parmJSON);
        setShowFlow(true);
        // setChoreographyEdit(true);
      });
    } catch (error) {}
  };

  // 修改编排机JSON
  const editChoreographyApi = (val: any) => {
    try {
      editChoreographyJSON(val).then((val) => {
        message.success('修改成功');
        // setChoreographyEdit(false);
        setServerData({});
      });
    } catch (error) {}
  };

  // 数据加载
  useEffect(() => {
    getDatas(
      { appId, choreographyServiceName, choreographyMethodName },
      { currentPageNo, pageSize },
    );
  }, []);

  // 刷新列表
  const refreshList = () => {
    getDatas(
      { appId, choreographyServiceName, choreographyMethodName },
      { currentPageNo, pageSize },
    );
  };

  /**
   *  @description 模态框操作
   */

  // 查看模态框确认按钮
  const viewOk = () => {
    setViewModal(false);
  };

  // 重置
  const reset = () => {
    setAppId('');
    setChoreographyServiceName('');
    setChoreographyMethodName('');
    setCurrentPageNo(1);
    setPageSize(10);
    refreshList();
  };

  // 列表删除按钮
  const handleRemove = (id: string) => {
    setDeleteid(id);
    setIsModalVisible(true);
  };

  // 确定删除用户数据
  const handleOk = () => {
    const Id = deleteid;
    deleteDatas({ Id });
  };

  // 添加
  const addModalOk = async () => {
    try {
      // 非空验证
      const validate = await addFormRef.current.validateFields();
      const param = await addFormRef.current.getFieldsValue();
      setRefreshNum(refreshNum + 1);
      setServerData({});
      // console.log(serverData);
      addDatas(param);
    } catch (err) {}
  };

  // 添加服务编排模态框确认按钮
  const addServerOk = () => {
    setRefreshNum(refreshNum + 1);
    const parm = {
      tenantId: addAfterId,
      json: childDatas,
    };
    setChoreographyApi(parm);
    editChoreographyApi(parm);
  };

  // 列表编辑按钮
  const editUser = async (item: any) => {
    setEditModal(true);
    editForm.setFieldsValue(item);
  };

  // 查看
  const viewUser = (id: string) => {
    viewDatas({ id });
    setViewModal(true);
  };

  // 保存编辑值-修改
  const editUserOK = () => {
    setEditModal(false);
    const param = editForm.getFieldsValue();
    editDatas(param);
  };

  // 获取已编排好的JSON对象
  const getChildData = () => {
    setChildDatas(serverData);
    // console.log(val);
  };

  // 列表修改编排按钮
  const editChoreography = (id: any) => {
    setRefreshNum(refreshNum + 1);
    localStorage.setItem('ChoreographyId', id);
    viewOrchestrationDatas({ id });
    setEditChoreographyDataId(id);
  };

  // 修改编排确认按钮
  const setChoreographyOk = () => {
    setRefreshNum(refreshNum + 1);
    const parm = {
      id: editChoreographyDataId,
      stateMachineJson: childDatas,
    };
    editChoreographyApi(parm);
  };

  // 添加模态框系统报文列表
  const AddModalRequestMessage = () => {
    const data = [
      {
        key: '1',
        Name: 'John',
        age: 32,
        address: 'New York No. 1 Lake Park',
        tags: 'nice',
        switch: true,
      },
      {
        key: '2',
        Name: 'Jim',
        age: 42,
        address: 'London No. 1 Lake Park',
        tags: 'loser',
        switch: true,
      },
      {
        key: '3',
        Name: 'Joe',
        age: 32,
        address: 'Sidney No. 1 Lake Park',
        tags: 'cool',
        switch: false,
      },
    ];

    return (
      <>
        <Table dataSource={data}>
          <Column title="表头1" dataIndex="csName" key="name" />
          <Column title="表头2" dataIndex="csAge" key="age" />
          <Column title="表头3" dataIndex="csAddress" key="address" />
          <Column title="表头4" dataIndex="csTags" key="tags" />
          <Column
            title="表头5"
            key="csAction"
            render={() => (
              <Space size="middle">
                <span>Invite </span>
                <span>Delete</span>
              </Space>
            )}
          />
          <Column
            title="表头6"
            key="csSwitch"
            render={(val) => (
              <Switch
                defaultChecked={val.switch}
                checkedChildren="开启"
                unCheckedChildren="关闭"
              />
            )}
          />
        </Table>
      </>
    );
  };

  // 添加模态框下方系统报文和响应报文tabs切换
  const AddModalMessage = () => {
    return (
      <>
        <Tabs defaultActiveKey="1">
          <TabPane tab="系统报文" key="1">
            <Button type="primary" htmlType="submit">
              添加
            </Button>
            <AddModalRequestMessage />
          </TabPane>
          <TabPane tab="响应报文" key="2">
            Content of Tab Pane 2
          </TabPane>
        </Tabs>
      </>
    );
  };

  return (
    <div className="bg-gray">
      {showFlow && (
        <Card
          title="编排服务"
          className="tableTitle"
          extra={
            <Button
              type="primary"
              onClick={() => {
                setShowFlow(false);
              }}
            >
              {' '}
              返回
            </Button>
          }
          bordered={false}
        >
          <Flow serverData={serverData} getData={getChildData} />
        </Card>
      )}
      {!showFlow && (
        <div>
          <div className="flex p-3 mb-2 bg-white searchTable">
            <Form layout="inline">
              <Space size={[8, 16]} wrap>
                <Form.Item label="应用ID:">
                  <Input
                    onChange={(event: any) => {
                      setAppId(event.target.value);
                    }}
                    value={appId}
                  />
                </Form.Item>
                <Form.Item label="服务名:">
                  <Input
                    onChange={(event: any) => {
                      setChoreographyServiceName(event.target.value);
                    }}
                    value={choreographyServiceName}
                  />
                </Form.Item>
                <Form.Item label="方法名:">
                  <Input
                    onChange={(event: any) => {
                      setChoreographyMethodName(event.target.value);
                    }}
                    value={choreographyMethodName}
                  />
                </Form.Item>
                <div style={{ paddingLeft: '58px' }}>
                  <Button
                    style={{ marginRight: 8 }}
                    onClick={() => {
                      // console.log({ appId, serviceName, methodName });
                      refreshList();
                    }}
                    type="primary"
                  >
                    查询
                  </Button>
                  <Button onClick={reset}>重置</Button>
                </div>
              </Space>
            </Form>
          </div>

          <Card
            title="编排服务"
            className="tableTitle"
            extra={
              <Button
                type="primary"
                onClick={() => {
                  setAddModal(true);
                  setServerData({});
                }}
              >
                {' '}
                +添加
              </Button>
            }
            bordered={false}
          >
            <Table
              columns={columns}
              dataSource={datas}
              scroll={{ x: 1500 }}
              pagination={false}
            />
            <Row
              justify="end"
              style={{ marginTop: '20px', paddingBottom: '10px' }}
            >
              <ConfigProvider locale={ZhCN}>
                <Pagination defaultCurrent={1} total={listTotal} />
              </ConfigProvider>
            </Row>
          </Card>

          {/* 添加确定后的服务编排编辑器模态框 */}
          <Modal
            className="addModal"
            style={{ marginLeft: 20, margin: '0 auto' }}
            cancelText="取消"
            okText="确认"
            title="服务编排"
            width="100"
            open={isModalServer}
            key={refreshNum}
            onOk={addServerOk}
            onCancel={() => {
              setRefreshNum(refreshNum + 1);
              setIsModalServer(false);
            }}
          >
            <Flow getData={getChildData} />
          </Modal>

          {/* 删除模态框 */}
          <Modal
            cancelText="取消"
            okText="确认"
            title="提示"
            open={isModalVisible}
            onOk={handleOk}
            onCancel={() => {
              setIsModalVisible(false);
            }}
          >
            是否确定删除本条数据？
          </Modal>

          {/* 查看模态框 */}
          <Modal
            destroyOnClose
            cancelText="取消"
            okText="确定"
            title="查看"
            open={ViewModal}
            onOk={viewOk}
            onCancel={() => {
              setViewModal(false);
            }}
          >
            <Form
              form={viewForm}
              labelCol={{ span: 5 }}
              wrapperCol={{ span: 19 }}
            >
              <Form.Item label="应用id" name="appId">
                <Input disabled />
              </Form.Item>
              <Form.Item label="服务名" name="choreographyServiceName">
                <Input disabled />
              </Form.Item>
              <Form.Item label="方法名" name="choreographyMethodName">
                <Input disabled />
              </Form.Item>
              <Form.Item label="接口全类名" name="className">
                <Input disabled />
              </Form.Item>
              <Form.Item label="请求报文" name="requestMessage">
                <Input disabled />
              </Form.Item>
              <Form.Item label="响应报文" name="responseMessage">
                <Input disabled />
              </Form.Item>
              <Form.Item label="描述" name="remark">
                <Input disabled />
              </Form.Item>
              <Form.Item label="版本号" name="version">
                <Input disabled />
              </Form.Item>
              <Form.Item label="创建人" name="createBy">
                <Input disabled />
              </Form.Item>
            </Form>
          </Modal>

          {/* 添加模态框 */}
          <Modal
            className="addModal"
            key={'addModal'}
            style={{ marginLeft: 20, margin: '0 auto', width: '820px' }}
            destroyOnClose
            cancelText="取消"
            okText="新增"
            title="编排服务新增"
            open={addModal}
            onOk={addModalOk}
            onCancel={() => {
              setAddModal(false);
            }}
          >
            <Form ref={addFormRef} size="middle" layout="vertical">
              <Row gutter={16}>
                <Col span={6}>
                  <Form.Item
                    label="所属应用id"
                    name="appID"
                    rules={[{ required: true, message: '请输入所属应用ID' }]}
                  >
                    <Input />
                  </Form.Item>
                </Col>
                <Col span={6}>
                  <Form.Item
                    label="编排机服务名"
                    name="stateMachineName"
                    rules={[{ required: true, message: '请输入编排机服务名' }]}
                  >
                    <Input />
                  </Form.Item>
                </Col>
                <Col span={6}>
                  <Form.Item
                    label="服务名"
                    name="choreographyServiceName"
                    rules={[{ required: true, message: '请输入服务名' }]}
                  >
                    <Input />
                  </Form.Item>
                </Col>
                <Col span={6}>
                  <Form.Item
                    label="方法名"
                    name="choreographyMethodName"
                    rules={[{ required: true, message: '请输入方法名' }]}
                  >
                    <Input />
                  </Form.Item>
                </Col>
                <Col span={6}>
                  <Form.Item
                    label="版本号"
                    name="version"
                    rules={[{ required: true, message: '请输入版本号' }]}
                  >
                    <Input />
                  </Form.Item>
                </Col>
                <Col span={6}>
                  <Form.Item label="描述" name="remark">
                    <Input />
                  </Form.Item>
                </Col>
              </Row>
            </Form>
            <AddModalMessage />
          </Modal>

          {/* 修改模态框 */}
          <Modal
            destroyOnClose
            cancelText="取消"
            key={'editModal'}
            okText="修改"
            title="用户编辑"
            open={editModal}
            onOk={editUserOK}
            onCancel={() => {
              setEditModal(false);
            }}
          >
            <Form
              form={editForm}
              labelCol={{ span: 5 }}
              wrapperCol={{ span: 19 }}
            >
              <Form.Item className="d-none" label="编排服务id" name="id">
                <Input />
              </Form.Item>
              <Form.Item label="应用id" name="appId">
                <Input />
              </Form.Item>
              <Form.Item label="服务名" name="choreographyServiceName">
                <Input />
              </Form.Item>
              <Form.Item label="方法名" name="choreographyMethodName">
                <Input />
              </Form.Item>
              <Form.Item label="接口全类名" name="className">
                <Input />
              </Form.Item>
              <Form.Item label="请求报文" name="requestMessage">
                <Input />
              </Form.Item>
              <Form.Item label="响应报文" name="responseMessage">
                <Input />
              </Form.Item>
              <Form.Item label="描述" name="remark">
                <Input />
              </Form.Item>
              <Form.Item label="版本号" name="version">
                <Input />
              </Form.Item>
            </Form>
          </Modal>

          {/* 修改编排模态框 */}
          <Modal
            className="addModal"
            style={{ marginLeft: 20, position: 'static' }}
            cancelText="取消"
            okText="确认"
            title="修改编排"
            width="80"
            open={choreographyEdit}
            key={refreshNum}
            onOk={setChoreographyOk}
            onCancel={() => {
              setRefreshNum(refreshNum + 1);
              setChoreographyEdit(false);
            }}
          >
            <Flow serverData={serverData} getData={getChildData} />
          </Modal>
        </div>
      )}
    </div>
  );
};
export default index;
